package com.bocai.user.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bocai.user.mapper.UserMapper;
import com.bocai.user.model.UserInfo;
import com.bocai.util.HashUtils;

@Service
public class UserService {
	private static Logger LOGGER = LoggerFactory.getLogger(UserService.class);
	private static final String MD5_SALT = "dasdtgrtsdgfsvsafd!@!$#312";	// 密码加密盐
	
	@Autowired
	private UserMapper userMapper;

	public boolean checkMobileExisted(String mobile) throws Exception {
		try {
			UserInfo userInfo = userMapper.selectUserByMobile(mobile);
			if(null != userInfo) {
				return true;
			}
			return false;
		} catch (Exception e) {
			LOGGER.error("Failed to selectUserByMobile:{}  ERROR:{}", mobile, e);
			throw e;
		}
	}

	@Transactional
	public boolean register(String mobile, String passwd) throws Exception {
		try {
			if(userMapper.insertUserInfo(mobile, HashUtils.getMD5(MD5_SALT + passwd)) > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			LOGGER.error("Failed to insertUserInfo:mobile={}, password={},  ERROR:{}", mobile, passwd, e);
			throw e;
		}
	}

	public boolean checkUserLogin(String mobile, String passwd) throws Exception {
		try {
			UserInfo userInfo = userMapper.selectUserByMobile(mobile);
			if(null == userInfo || ! userInfo.getSzPassword().equals(HashUtils.getMD5(MD5_SALT + passwd))) {	// 用户不存在，或者密码不匹配
				return false;
			}
			return true;
		} catch (Exception e) {
			LOGGER.error("Failed to selectUserByMobile:{}  ERROR:{}", mobile, e);
			throw e;
		}
	}

	public UserInfo getUserInfoByMobile(String mobile) throws Exception {
		return userMapper.selectUserByMobile(mobile);
	}
	
	public boolean updatebankinfo(String mobile, String bankname, String bankno) throws Exception {
		try {
			if(userMapper.updateBankInfo(mobile, bankname, bankno) > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			LOGGER.error("Failed to updatebankinfo:mobile={}, bankname={}, bankno={}, ERROR:{}", mobile, bankname, bankno, e);
			throw e;
		}
	}
	
	public boolean updatePassword(String mobile, String password, String newpassword) throws Exception {
		try {
			if(userMapper.updatePassword(mobile, password, newpassword) > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			LOGGER.error("Failed to updatebankinfo:mobile={}, bankname={}, bankno={}, ERROR:{}", mobile, password, newpassword, e);
			throw e;
		}
	}

}
